在 SwiftUI 中,你可以輕鬆地使用 Color 和 Font 來自訂視圖的顏色和字體樣式。以下是如何在視圖中應用這些屬性的教學。
Color你可以通過 foregroundColor 修改文本、圖標或其他視圖的顏色:
Text("Hello, SwiftUI!")
.foregroundColor(.blue)
在這段代碼中,Text 的字體顏色被設置為藍色。SwiftUI 提供了多種預設顏色,如 .red, .green, .black,也可以使用自訂顏色:
Text("Custom Color")
.foregroundColor(Color(red: 0.5, green: 0.2, blue: 0.7))
這段代碼使用 RGB 值創建了一個自訂的顏色。
FontFont 可以用來設定文本的字體樣式,包括字體大小、粗細等:
Text("Large Title")
.font(.largeTitle)
這段代碼將文本設置為大的標題樣式。SwiftUI 提供了多種內建字體樣式,如 .title, .headline, .body, .caption,以及你可以自訂的字體大小和粗細:
Text("Custom Font")
.font(.system(size: 24, weight: .bold, design: .rounded))
在這裡,文本被設置為 24 點字號,字體為粗體,設計風格為圓角。
下面是一個結合使用顏色和字體的 SwiftUI 視圖範例:
import SwiftUI
struct ColorFontView: View {
var body: some View {
VStack(spacing: 20) {
Text("Hello, SwiftUI!")
.foregroundColor(.blue)
.font(.largeTitle)
Text("Customized Font and Color")
.foregroundColor(Color(red: 0.5, green: 0.2, blue: 0.7))
.font(.system(size: 24, weight: .bold, design: .rounded))
Text("Subtitle Style")
.foregroundColor(.gray)
.font(.subheadline)
}
.padding()
}
}
struct ColorFontView_Previews: PreviewProvider {
static var previews: some View {
ColorFontView()
}
}
VStack:用來垂直排列多個 Text 視圖。Text 視圖:
Text 使用內建的 .largeTitle 字體樣式和藍色。Text 使用自訂的字體樣式、大小和顏色。Text 使用內建的 .subheadline 字體樣式和灰色。Preview:ColorFontView_Previews 用來即時查看設計效果。